# -*- coding: utf-8 -*-
"""
Created on Sun Sep 18 05:14:42 2016

@author: zhiqiang
"""

#k-mean聚类
#首先要把result数据处理成二维数组形式
#再定义一个距离公式
kmeanData = []
for j in range(1,1001):
    a_j = []
    for i in first_ans:
        a_j.append(result[i][j-1])
    kmeanData.append(a_j)
label = list(range(1,1001))
#kmeanData是个1000X35的一个矩阵


def distance_fun(person1,person2):
    d = 0
    for p in range(len(person1)):
        if person1[p]==person2[p]:
            d += 1
    return d



import random
def revise_kcluster(rows,batesP=batesP,distance=distance_fun,weiDianList=first_ans,k=2):
  # Determine the minimum and maximum values for each point
  ranges=[list(batesP[key].keys()) for key in weiDianList]

  # Create k randomly placed centroids
  clusters=[[ranges[i][random.randint(0,2)] for i in range(len(rows[0]))] for j in range(k)]
  
  lastmatches=None
  for t in range(100):
    print('Iteration %d' % t)
    bestmatches=[[] for i in range(k)]
    
    # Find which centroid is the closest for each row
    for j in range(len(rows)):
      row=rows[j]
      bestmatch=0
      for i in range(k):
        d=distance(clusters[i],row)
        if d<distance(clusters[bestmatch],row): bestmatch=i
      bestmatches[bestmatch].append(j)

    # If the results are the same as last time, this is complete
    if bestmatches==lastmatches: break
    lastmatches=bestmatches
    
    # Move the centroids to the average of their members
    for i in range(k):
      avgs=[0.0]*len(rows[0])
      if len(bestmatches[i])>0:
        for rowid in bestmatches[i]:
          for m in range(len(rows[rowid])):
            avgs[m]+=rows[rowid][m]
        for j in range(len(avgs)):
          avgs[j]/=len(bestmatches[i])
        clusters[i]=avgs
      
  return bestmatches